package com.planet_ink.ZipCodeWeather.resources;

import java.net.URLEncoder;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.planet_ink.ZipCodeWeather.services.HttpClientFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


@Path("yql")
@Produces(MediaType.APPLICATION_JSON)
public class YQLPassThrough
{
	private static String resourcePrefix 	= "http://query.yahooapis.com/v1/public/yql?q=";
	private static String resourcePostfix 	= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

	@Path("{query}")
	@GET
	/**
	 * A web resource accessed by /city/api/yql/{query}
	 * Returns current, todays, and tomorrows weather conditions
	 * @param zipCode the zip code to get weather information about
	 * @return a JSON document containing weather conditions for this zip code
	 */
	public Response getWeatherSingle(@PathParam("query") String query)
	{
		if((query==null)||(query.length()==0))
		{
			return Response.noContent().status(Status.BAD_REQUEST).build();
		}
		try
		{
			final String finalYQL = URLEncoder.encode(query,"UTF-8");
			Client httpClient = null;
			try
			{
				httpClient = HttpClientFactory.defaultInstance().getHttpClient();
				final WebResource webResource = httpClient.resource(resourcePrefix + finalYQL + resourcePostfix);
				final ClientResponse webResponse = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
				if(webResponse.getStatus() != Status.OK.getStatusCode())
				{
					return Response.noContent().status(Status.fromStatusCode(webResponse.getStatus())).build();
				}
				final String jsonResponse = webResponse.getEntity(String.class);
				return Response.ok().entity(jsonResponse).build();
			}
			finally
			{
				if(httpClient != null)
				{
					HttpClientFactory.defaultInstance().giveBackClient(httpClient);
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace(System.err);
			return Response.noContent().status(Status.INTERNAL_SERVER_ERROR).build();
		}
	}
}
